/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://github.com/mineadmin
 */
import type { MaProTableColumns, MaProTableExpose } from "@mineadmin/pro-table";
import type { UseDialogExpose } from "@/hooks/useDialog.ts";

import defaultAvatar from "@/assets/images/defaultAvatar.jpg";
import { ElTag } from "element-plus";
import { useMessage } from "@/hooks/useMessage.ts";
import { ResultCode } from "@/utils/ResultCode.ts";
import hasAuth from "@/utils/permission/hasAuth.ts";
import { deleteByIds } from "$/attractions/broadcast/api/broadcastPlans.ts";
import { getFullFileUrl } from "@/utils/fileUrl";
import { ref } from "vue";

export default function getTableColumns(
  dialog: UseDialogExpose,
  formRef: any,
  t: any
): MaProTableColumns[] {
  const msg = useMessage();
  
  // 全局音频管理
  let currentAudio: HTMLAudioElement | null = null;
  const playingRowId = ref<number | null>(null);

  return [
    {
      type: "selection",
      showOverflowTooltip: false,
      label: () => t("crud.selection"),
    },
    {
      label: "音频文件",
      prop: "content_audio_file",
      multiple: false,
      cellRender: ({ row }) => {
        const isPlaying = playingRowId.value === row.id;
        
        const handleAudioToggle = () => {
          if (isPlaying) {
            // 停止播放
            if (currentAudio) {
              currentAudio.pause();
              currentAudio.currentTime = 0;
              currentAudio = null;
            }
            playingRowId.value = null;
          } else {
            // 开始播放
            if (row?.content_audio_file) {
              // 先停止当前播放的音频
              if (currentAudio) {
                currentAudio.pause();
                currentAudio.currentTime = 0;
              }
              
              const fullUrl = getFullFileUrl(row.content_audio_file);
              currentAudio = new Audio(fullUrl);
              
              currentAudio.addEventListener('ended', () => {
                playingRowId.value = null;
                currentAudio = null;
              });
              
              currentAudio.addEventListener('error', () => {
                msg.error("音频播放失败");
                playingRowId.value = null;
                currentAudio = null;
              });
              
              currentAudio.play().then(() => {
                playingRowId.value = row.id;
              }).catch(error => {
                console.error('音频播放失败:', error);
                msg.error("音频播放失败");
                playingRowId.value = null;
                currentAudio = null;
              });
            } else {
              msg.info("无音频文件");
            }
          }
        };
        
        return row?.content_audio_file ? (
          <el-link
            onClick={handleAudioToggle}
            type={isPlaying ? "danger" : "success"}
            icon={isPlaying ? "ep:video-pause" : "ep:video-play"}
          >
            {isPlaying ? "停止播放" : "播放音频"}
          </el-link>
        ) : (
          <span style="color: #999;">无音频文件</span>
        );
      },
    },
    { label: "开始时间", prop: "start_time" },
    { label: "结束时间", prop: "end_time" },
    {
      label: "执行日期",
      prop: "execution_day",
      mode: "date",
      showTime: false,
    },
    {
      label: "重复类型",
      prop: "repeat_type",
      cellRender: ({ row }) => {
        const statusMap = {
          1: { text: "不重复", type: "success" },
          2: { text: "每天", type: "warning" },
          3: { text: "每周", type: "info" },
          4: { text: "每月", type: "danger" },
        };
        const status = statusMap[row.repeat_type] || {
          text: "未知",
          type: "info",
        };
        return h(ElTag, { type: status.type }, () => status.text);
      },
    },
    {
      label: "重复间隔",
      prop: "repeat_interval",
      cellRender: ({ row }) => {
        return row.repeat_interval + "分钟";
      },
    },
    { label: "重复次数", prop: "repeat_count" },
    { label: "触发事件", prop: "trigger_event" },
    { label: "触发条件", prop: "trigger_condition" },
    { label: "音量", prop: "volume_day" },
    {
      label: "最后执行时间",
      prop: "last_execution_time",
      mode: "date",
      showTime: true,
    },
    { label: "已执行次数", prop: "execution_count" },
    {
      type: "operation",
      label: () => t("crud.operation"),
      operationConfigure: {
        actions: [
          {
            name: "edit",
            icon: "material-symbols:person-edit",
            show: ({ row }) => hasAuth("broadcast_plans:broadcastPlans:update"),
            text: () => t("crud.edit"),
            onClick: ({ row }) => {
              dialog.setTitle(t("crud.edit"));
              dialog.open({ formType: "edit", data: row });
            },
          },
          {
            name: "del",
            icon: "mdi:delete",
            text: () => t("crud.delete"),
            show: ({ row }) => hasAuth("broadcast_plans:broadcastPlans:delete"),
            onClick: ({ row }, proxy: MaProTableExpose) => {
              msg.delConfirm(t("crud.delDataMessage")).then(async () => {
                const response = await deleteByIds([row.id]);
                if (response.code === ResultCode.SUCCESS) {
                  msg.success(t("crud.delSuccess"));
                  proxy.refresh();
                }
              });
            },
          },
        ],
      },
    },
  ];
}
